package com.dh.weibo.dao;

import com.dh.weibo.exception.AccountReadyException;
import com.dh.weibo.pojo.User;
import com.dh.weibo.util.Md5Util;

import java.util.ArrayList;
import java.util.List;

// 用户数据类
public class UserDao {
    private List<User> users = new ArrayList<>();

    // 实例代码块
    {
        User user = new User("admin", "1", "admin");
        user.setSuper(true);
        user.setUid("1");
        users.add(user);

        User user1 = new User("zkm", "1", "zkm");
        user1.setUid("12345");
        users.add(user1);
    }

    /**
     * 注册
     *
     * @param user
     * @throws AccountReadyException
     */
    public void register(User user) throws AccountReadyException {
        if (user != null) {
            if (!isReadyUser(user)) {// 判断账号是否存在
                users.add(user);
            } else {
                throw new AccountReadyException("账号已存在");
            }
        }
    }

    /**
     * 登陆
     *
     * @param account
     * @param passWord
     * @return
     */
    public User login(String account, String passWord) {
        for (User user : users) {
            if (user.getAccount().equals(account) && user.getPassWord().equals(Md5Util.getMD5Str(passWord))) {
                return user;
            }
        }
        return null;
    }

    /**
     * 判断账号是否存在
     *
     * @param user
     * @return
     */
    private boolean isReadyUser(User user) {
        for (User u : users) {
            if (u.getAccount().equals(user.getAccount())) {
                return true;
            }
        }
        return false;
    }

    public List<User> getUsers() {
        return users;
    }

    /**
     * 根据ID获取当个用户
     * @param id
     * @return
     */
    public User getUserByID(String id) {
        for (User user : users) {
            if (user.getUid().equals(id)) {
                return user;
            }
        }
        return null;
    }
}
